package com.castle.fortress.admin.study.course.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.annotation.CastleLog;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.study.course.dto.StudyCourseChapterDto;
import com.castle.fortress.admin.study.course.dto.StudyCourseDto;
import com.castle.fortress.admin.study.course.dto.StudyCoursewareDto;
import com.castle.fortress.admin.study.course.entity.StudyCourseEntity;
import com.castle.fortress.admin.study.course.service.StudyCourseChapterCoursewareService;
import com.castle.fortress.admin.study.course.service.StudyCourseChapterService;
import com.castle.fortress.admin.study.course.service.StudyCourseService;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.CourseStatusEnum;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 课程管理 控制器
 *
 * @author castle
 * @since 2023-01-30
 */
@Api(tags="课程管理管理控制器")
@Controller
public class StudyCourseController {
	@Autowired
	private StudyCourseService studyCourseService;
	@Autowired
	private StudyCourseChapterService studyCourseChapterService;
	@Autowired
	private StudyCourseChapterCoursewareService studyCourseChapterCoursewareService;

	/**
	 * 课程管理的分页展示
	 * @param studyCourseDto 课程管理实体类
	 * @param current 当前页
	 * @param size  每页记录数
	 * @return
	 */
    @CastleLog(operLocation="课程管理",operType = OperationTypeEnum.QUERY)
	@ApiOperation("课程管理分页展示")
	@GetMapping("/study/course/studyCourse/page")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:pageList")
	public RespBody<IPage<StudyCourseDto>> pageStudyCourse(StudyCourseDto studyCourseDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
		Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
		Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
		Page<StudyCourseDto> page = new Page(pageIndex, pageSize);
			IPage<StudyCourseDto> pages = studyCourseService.pageStudyCourseExtends(page, studyCourseDto);

		return RespBody.data(pages);
	}

	/**
	 * 课程管理的列表展示
	 * @param studyCourseDto 课程管理实体类
	 * @return
	 */
    @CastleLog(operLocation="课程管理",operType = OperationTypeEnum.QUERY)
	@ApiOperation("课程管理列表展示")
	@GetMapping("/study/course/studyCourse/list")
	@ResponseBody
	public RespBody<List<StudyCourseDto>> listStudyCourse(StudyCourseDto studyCourseDto){
		List<StudyCourseDto> list = studyCourseService.listStudyCourse(studyCourseDto);
		return RespBody.data(list);
	}

	/**
	 * 课程管理保存
	 * @param studyCourseDto 课程管理实体类
	 * @return
	 */
    @CastleLog(operLocation="课程管理",operType = OperationTypeEnum.INSERT)
	@ApiOperation("课程管理保存")
	@PostMapping("/study/course/studyCourse/save")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:save")
	public RespBody<String> saveStudyCourse(@RequestBody StudyCourseDto studyCourseDto){
		if(studyCourseDto == null ){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
          StudyCourseEntity studyCourseEntity = ConvertUtil.transformObj(studyCourseDto,StudyCourseEntity.class);
		//初始化为草稿状态
		if(studyCourseEntity.getCourseStatus()==null){
			studyCourseEntity.setCourseStatus(CourseStatusEnum.DRAFT.getCode());
		}
		//非上架课程将设置首页不推荐
		if(!CourseStatusEnum.PUTAWAY.getCode().equals(studyCourseEntity.getCourseStatus())){
			studyCourseEntity.setIsRecommend(YesNoEnum.NO.getCode());
		}
		if(studyCourseService.save(studyCourseEntity)){
			return RespBody.data(studyCourseEntity.getId()+"");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 课程管理编辑
	 * @param studyCourseDto 课程管理实体类
	 * @return
	 */
    @CastleLog(operLocation="课程管理",operType = OperationTypeEnum.UPDATE)
	@ApiOperation("课程管理编辑")
	@PostMapping("/study/course/studyCourse/edit")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:edit")
	public RespBody<String> updateStudyCourse(@RequestBody StudyCourseDto studyCourseDto){
		if(studyCourseDto == null || studyCourseDto.getId() == null || studyCourseDto.getId().equals(0L)){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
          StudyCourseEntity studyCourseEntity = ConvertUtil.transformObj(studyCourseDto,StudyCourseEntity.class);
		//非上架课程将设置首页不推荐
		if(!CourseStatusEnum.PUTAWAY.getCode().equals(studyCourseEntity.getCourseStatus())){
			studyCourseEntity.setIsRecommend(YesNoEnum.NO.getCode());
		}
		if(studyCourseService.updateById(studyCourseEntity)){
			return RespBody.data(studyCourseEntity.getId()+"");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 课程管理删除
	 * @param id
	 * @return
	 */
    @CastleLog(operLocation="课程管理",operType = OperationTypeEnum.DELETE)
	@ApiOperation("课程管理删除")
	@PostMapping("/study/course/studyCourse/delete")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:delete")
	public RespBody<String> deleteStudyCourse(@RequestParam Long id){
		if(id == null ){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(studyCourseService.removeById(id)) {
			studyCourseChapterService.delByCourseId(id);
			studyCourseChapterCoursewareService.delByCourseId(id);
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}


	/**
	 * 课程管理批量删除
	 * @param ids
	 * @return
	 */
    @CastleLog(operLocation="课程管理",operType = OperationTypeEnum.DELETE)
	@ApiOperation("课程管理批量删除")
	@PostMapping("/study/course/studyCourse/deleteBatch")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:deleteBatch")
	public RespBody<String> deleteStudyCourseBatch(@RequestBody List<Long> ids){
		if(ids == null || ids.size()<1){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(studyCourseService.removeByIds(ids)) {
			studyCourseChapterService.delByCourseIds(ids);
			studyCourseChapterCoursewareService.delByCourseIds(ids);
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 课程管理详情
	 * @param id 课程管理id
	 * @return
	 */
    @CastleLog(operLocation="课程管理",operType = OperationTypeEnum.QUERY)
	@ApiOperation("课程管理详情")
	@GetMapping("/study/course/studyCourse/info")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:info")
	public RespBody<StudyCourseDto> infoStudyCourse(@RequestParam Long id){
		if(id == null){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
        StudyCourseDto studyCourseDto =  studyCourseService.getByIdExtends(id);
		return RespBody.data(studyCourseDto);
	}

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="课程管理",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/study/course/studyCourse/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<StudyCourseDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<StudyCourseDto> list = studyCourseService.listStudyCourse(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


	/**
	 * 修改置顶状态
	 * @param studyCourseDto 课程管理实体类
	 * @return
	 */
	@CastleLog(operLocation="课程管理",operType = OperationTypeEnum.UPDATE)
	@ApiOperation("修改置顶状态")
	@PostMapping("/study/course/studyCourse/editRecommend")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:uptTop")
	public RespBody<String> updateIsRecommend(@RequestBody StudyCourseDto studyCourseDto){
		if(studyCourseDto == null || studyCourseDto.getId() == null || studyCourseDto.getId().equals(0L)){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(studyCourseService.updateOpt(studyCourseDto.getId(),"00",studyCourseDto.getIsRecommend()+"")){
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 修改课程状态
	 * @param dto 课程管理实体类
	 * @return
	 */
	@CastleLog(operLocation="课程管理",operType = OperationTypeEnum.UPDATE)
	@ApiOperation("修改课程状态")
	@PostMapping("/study/course/studyCourse/editCourseStatus")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:uptStatus")
	public RespBody<String> updateCourseStatus(@RequestBody StudyCourseDto dto){
		if(dto == null || dto.getId() == null || dto.getId().equals(0L)){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		// 上架时判断课程有没有章节没有课件
		if (dto.getCourseStatus() == CourseStatusEnum.PUTAWAY.getCode() ){
			StudyCourseDto studyCourseDto =  studyCourseService.getByIdExtends(dto.getId());
			if(studyCourseDto != null){
				List<StudyCourseChapterDto> list = studyCourseChapterService.getListByCourseId(studyCourseDto.getId());
				if (list == null || list.size() < 1){
					return RespBody.fail("操作失败，请先添加章节");
				}else {
					for (StudyCourseChapterDto courseChapterDto : list){
						List<StudyCoursewareDto> coursewareDtoList = courseChapterDto.getCoursewares();
						if (coursewareDtoList == null || coursewareDtoList.size() < 1){
							return RespBody.fail("操作失败，课程中含有未添加课件的章节");
						}
					}
				}
			}else {
				return RespBody.fail("操作失败，课程不存在");
			}
		//非上架课程需要设置为首页不推荐
		}else{
			studyCourseService.updateOpt(dto.getId(),"00",YesNoEnum.NO.getCode()+"");
		}
		if(studyCourseService.updateOpt(dto.getId(),"01",dto.getCourseStatus()+"")){
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * 修改推荐类型
	 * @param studyCourseDto 课程管理实体类
	 * @return
	 */
	@CastleLog(operLocation="课程管理",operType = OperationTypeEnum.UPDATE)
	@ApiOperation("修改推荐类型")
	@PostMapping("/study/course/studyCourse/editRecommendType")
	@ResponseBody
	public RespBody<String> editRecommendType(@RequestBody StudyCourseDto studyCourseDto){
		if(studyCourseDto == null || studyCourseDto.getId() == null || studyCourseDto.getId().equals(0L)){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(studyCourseService.updateOpt(studyCourseDto.getId(),"02",studyCourseDto.getRecommendType())){
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	@CastleLog(operLocation="会员课程学习管理",operType = OperationTypeEnum.QUERY)
	@ApiOperation("会员课程学习管理分页展示")
	@GetMapping("/study/course/studyCourse/memberStudyPage")
	@ResponseBody
	@RequiresPermissions("study:course:studyCourse:memberStudyPage")
	public RespBody<IPage<StudyCourseDto>> memberStudyPage(StudyCourseDto studyCourseDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
		Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
		Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
		Page<StudyCourseDto> page = new Page(pageIndex, pageSize);
		IPage<StudyCourseDto> pages = studyCourseService.memberStudyPage(page, studyCourseDto);
		return RespBody.data(pages);
	}

}
